package zhihuilan.controlle.wechatMini;

import com.alibaba.fastjson.JSONObject;
//import com.aliyun.imagesearch20201214.models.SearchImageByPicResponseBody;
//import com.aliyun.imagesearch20201214.models.SearchImageByTextResponseBody;
import com.aliyuncs.exceptions.ClientException;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import zhihuilan.common.WxMiniResponse;
import zhihuilan.common.utils.AliPushSearchDoc;
import zhihuilan.common.utils.AliyunUtils;
import zhihuilan.config.StaticFiledConfig;
import zhihuilan.controlle.BasicController;
import zhihuilan.dto.MySearchDto;
import zhihuilan.dto.MyStaffShopDto;
import zhihuilan.dto.WxMiniPageDto;
import zhihuilan.entity.*;
import zhihuilan.params.query.MySearchQueryParam;
import org.jsoup.safety.Safelist;
import zhihuilan.params.query.MyStaffQueryParam;
import zhihuilan.params.query.MyStaffShopGoodsQueryParam;
import zhihuilan.params.query.MyStaffShopQueryParam;
import zhihuilan.service.*;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/app/Search")
public class MySearchController extends BasicController {

    private  String[] element = {"＊", "*", "x", "X", "×", "✘"};

    @Autowired
    private MySearchService mySearchService;


    @Resource
    private StaticFiledConfig myStaticConfig;


    @Autowired
    private MyStaffSearchService myStaffSearchService;

    @Autowired
    private MyCircleService myCircleService;



    /**
     * @api  /Search/getSearchList 获取搜索list
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  pagesize 每页有几条信息
     * @apiParam {int}  page 第几页
     * @apiParam {String}  keyword 关键词
     *  @apiParam {int}  type 0=动态，1=商品
     */
    @PostMapping("/getImageSearchList")
    public WxMiniResponse getImageSearchList(@RequestBody MySearchQueryParam mySearchQueryParam) throws Exception {
        AliPushSearchDoc aliPushSearchDoc = new AliPushSearchDoc();
        //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
        if (!this.isCheckLogin(mySearchQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
//            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        if(currentStaff!=null&&currentStaff.getId()>0){
            myStaffSearchService.setSearchKeyword(mySearchQueryParam.getKeyword(),currentStaff.getId(),"search",0);
        }

        mySearchQueryParam.setType(0);
        System.out.println(mySearchQueryParam);
        Map  s =  aliPushSearchDoc.queryImageByGoods(mySearchQueryParam);
        //   aliyunUtils.TextEmbedding(mySearchQueryParam.getKeyword(),myStaticConfig.getApiKey(),1);
        return WxMiniResponse.ok(s);
    }

    /**
     * @api  /Search/getSearchList 获取搜索list
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  pagesize 每页有几条信息
     * @apiParam {int}  page 第几页
     * @apiParam {String}  keyword 关键词
     *  @apiParam {int}  type 0=动态，1=商品
     */
    @PostMapping("/getSearchList")
    public WxMiniResponse getSearchList(@RequestBody MySearchQueryParam mySearchQueryParam) throws Exception {
         AliPushSearchDoc aliPushSearchDoc = new AliPushSearchDoc();
        //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
        if (!this.isCheckLogin(mySearchQueryParam.getGuid())) {
            //如果用户未登陆，提示用户未登陆信息，并且返回未登陆的枚举编码；
//            return WxMiniResponse.error(ResultEnum.UNLOGIN.getKey(), ResultEnum.UNLOGIN.getValue());
        }
        if(currentStaff!=null&&currentStaff.getId()>0){
            myStaffSearchService.setSearchKeyword(mySearchQueryParam.getKeyword(),currentStaff.getId(),"search",0);
        }

        if(!ObjectUtils.isEmpty(mySearchQueryParam.getType())&&mySearchQueryParam.getType().equals(0)){
            Map  s =  aliPushSearchDoc.queryTextByCircle(mySearchQueryParam);
            return WxMiniResponse.ok(s);
        }
        mySearchQueryParam.setType(0);
        System.out.println(mySearchQueryParam);
        Map  s =  aliPushSearchDoc.queryTextByGoods(mySearchQueryParam);
     //   aliyunUtils.TextEmbedding(mySearchQueryParam.getKeyword(),myStaticConfig.getApiKey(),1);
        return WxMiniResponse.ok(s);
//        List<SearchImageByPicResponseBody.SearchImageByPicResponseBodyAuctions> list;
//        List<SearchImageByTextResponseBody.SearchImageByTextResponseBodyAuctions> listSearch;
//        if(mySearchQueryParam.getKeyword().indexOf("https://")>=0){
//            list =  aliyunUtils.SearchImageByPic(mySearchQueryParam,myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());
//
//            return WxMiniResponse.ok(list);
//        }else {
//
//            listSearch =  aliyunUtils.SearchImageByText(mySearchQueryParam,myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());
//
//            List<MySearchDto> sss = listSearch.stream().map(pa->{
//                MySearchDto searchDto = new MySearchDto();
//                searchDto.setPid(Integer.parseInt(pa.getProductId()) );
//                searchDto.setName(pa.getPicName());
//                searchDto.setId(Integer.parseInt(pa.getProductId()));
//                searchDto.setImg(pa.getStrAttr4());
//                searchDto.setLogo(pa.getStrAttr4());
//                searchDto.setStaffId(pa.getIntAttr());
//                return  searchDto;
//            }).collect(Collectors.toList());
//            Map map = new HashMap();
//            map.put("data",sss);
//            map.put("total",1000);
//            return WxMiniResponse.ok(map);
//
//        }
//        List keywordList = new ArrayList<>();
//        List keywordList1 = new ArrayList<>();
//        if(mySearchQueryParam.getKeyword()!=null) {
//            String keyword = Jsoup.clean(mySearchQueryParam.getKeyword(), Safelist.none());
//            for (int i = 0; i < element.length; i++) {
//                keyword = keyword.replace(element[i], "×");
//            }
//            JSONObject jsonObject = aliyunUtils.aliNlp(keyword,myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());
//            if(jsonObject.getString("success").equals("true")){
//                keywordList = (List) jsonObject.get("result");
//                List finalKeywordList = new ArrayList();
//                for(Object ob:keywordList)
//                    {
//                        Map map = (Map) ob;
//                        if(!map.get("synonym").equals("")){
//                            Map map1 = new HashMap();
//                            map1.put("synonym","");
//                            map1.put("weight",map.get("weight"));
//                            map1.put("tag",map.get("tag"));
//                            map1.put("word",map.get("synonym"));
//                            finalKeywordList.add(map1);
//
//                        }
//                }
//                keywordList.addAll(finalKeywordList);
//                keywordList1 = (List) keywordList.stream()
//                        .sorted((o1, o2) -> {
//                            JSONObject obj1 = new JSONObject((Map) o1); // 直接转 JSONObject
//                            JSONObject obj2 = new JSONObject((Map) o2);
//                            double weight1 = obj1.getDouble("weight");
//                            double weight2 = obj2.getDouble("weight");
//                            return Double.compare(weight2, weight1);
//                        }).collect(Collectors.toList());
//
//            }
//
//            keyword = keyword.replace(" ", "%");
//            mySearchQueryParam.setKeyword(keyword);
//        }
      // WxMiniPageDto<MySearchDto>  searchPageDto = mySearchService.getSearchList(mySearchQueryParam,strArray);
//        Map map = new HashMap();
//        map.put("data",searchList);

    }

    /**
     * @api /Search/getSearchIndexList 获取搜索list
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  shopSize 每页有几条信息
     * @apiParam {int}  goodsSize 每页有几条商品
     * @apiParam {int}  page 第几页
     * @apiParam {String}  keyword 关键词
     */
    @PostMapping("/getSearchIndexList")
    public WxMiniResponse getSearchIndexList(@RequestBody MySearchQueryParam mySearchQueryParam) throws ClientException {
        AliyunUtils aliyunUtils = new AliyunUtils();
        isCheckLogin(mySearchQueryParam.getGuid());
        if(currentStaff!=null&&currentStaff.getId()>0){
            myStaffSearchService.setSearchKeyword(mySearchQueryParam.getKeyword(),currentStaff.getId(),"search",0);
        }
        List keywordList = new ArrayList<>();
        List keywordList1 = new ArrayList<>();
        if(mySearchQueryParam.getKeyword()!=null) {
            String keyword = Jsoup.clean(mySearchQueryParam.getKeyword(), Safelist.none());
            for (int i = 0; i < element.length; i++) {
                keyword = keyword.replace(element[i], "×");
            }
            JSONObject jsonObject = aliyunUtils.aliNlp(keyword,myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());
            if(jsonObject.getString("success").equals("true")){
                keywordList = (List) jsonObject.get("result");
                List finalKeywordList = new ArrayList();
                for(Object ob:keywordList)
                {
                    Map map = (Map) ob;
                    if(!map.get("synonym").equals("")){
                        Map map1 = new HashMap();
                        map1.put("synonym","");
                        map1.put("weight",map.get("weight"));
                        map1.put("tag",map.get("tag"));
                        map1.put("word",map.get("synonym"));
                        finalKeywordList.add(map1);

                    }
                }
                keywordList.addAll(finalKeywordList);
                keywordList1 = (List) keywordList.stream()
                        .sorted((o1, o2) -> {
                            JSONObject obj1 = new JSONObject((Map) o1); // 直接转 JSONObject
                            JSONObject obj2 = new JSONObject((Map) o2);
                            double weight1 = obj1.getDouble("weight");
                            double weight2 = obj2.getDouble("weight");
                            return Double.compare(weight2, weight1);
                        }).collect(Collectors.toList());

            }

            keyword = keyword.replace(" ", "%");
            mySearchQueryParam.setKeyword(keyword);
        }
        Map searchPageDto = mySearchService.getSearchIndexList(mySearchQueryParam,keywordList1);
        return WxMiniResponse.ok(searchPageDto);
    }

    /**
     * @api {GET} /Search/getSearchShopList 获取搜索商品商铺list
     * @apiVersion 1.0.0
     * @apiName getSearchShopList
     * @apiGroup Pay
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  pagesize 每页有几条信息
     * @apiParam {int}  page 第几页
     * @apiParam {String}  keyword 关键词
     * @apiParam {String}  lat 经度
     * @apiParam {String}  lng 纬度
     */
    @PostMapping("/getSearchShopList")
    public WxMiniResponse getSearchShopList(@RequestBody MySearchQueryParam mySearchQueryParam) throws Exception {
        AliPushSearchDoc aliPushSearchDoc = new AliPushSearchDoc();
        isCheckLogin(mySearchQueryParam.getGuid());
        if(currentStaff!=null&&currentStaff.getId()>0){
            myStaffSearchService.setSearchKeyword(mySearchQueryParam.getKeyword(),currentStaff.getId(),"search",0);
        }
        Map  s = new HashMap();
        if(mySearchQueryParam.getType()==1){
              s =  aliPushSearchDoc.queryTextByGoods(mySearchQueryParam);
        }else {
              s =  aliPushSearchDoc.queryTextByShops(mySearchQueryParam);
        }

        return WxMiniResponse.ok(s);
     //   List list =  aliyunUtils.SearchImageByText(mySearchQueryParam,myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());
//        List keywordList = new ArrayList<>();
//        List keywordList1 = new ArrayList<>();
//        if(mySearchQueryParam.getKeyword()!=null) {
//            String keyword = Jsoup.clean(mySearchQueryParam.getKeyword(), Safelist.none());
//            for (int i = 0; i < element.length; i++) {
//                keyword = keyword.replace(element[i], "×");
//            }
//            JSONObject jsonObject = aliyunUtils.aliNlp(keyword,myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());
//            if(jsonObject.getString("success").equals("true")){
//                keywordList = (List) jsonObject.get("result");
//                List finalKeywordList = new ArrayList();
//                for(Object ob:keywordList)
//                {
//                    Map map = (Map) ob;
//                    if(!map.get("synonym").equals("")){
//                        Map map1 = new HashMap();
//                        map1.put("synonym","");
//                        map1.put("weight",map.get("weight"));
//                        map1.put("tag",map.get("tag"));
//                        map1.put("word",map.get("synonym"));
//                        finalKeywordList.add(map1);
//
//                    }
//                }
//                keywordList.addAll(finalKeywordList);
//                keywordList1 = (List) keywordList.stream()
//                        .sorted((o1, o2) -> {
//                            JSONObject obj1 = new JSONObject((Map) o1); // 直接转 JSONObject
//                            JSONObject obj2 = new JSONObject((Map) o2);
//                            double weight1 = obj1.getDouble("weight");
//                            double weight2 = obj2.getDouble("weight");
//                            return Double.compare(weight2, weight1);
//                        }).collect(Collectors.toList());
//
//            }
//
//            keyword = keyword.replace(" ", "%");
//            mySearchQueryParam.setKeyword(keyword);
//        }
//        WxMiniPageDto<MySearchDto> resultPage = mySearchService.getSearchShopList(mySearchQueryParam,keywordList1);
        //return null;
    }

    /**
     * @api {GET} /Search/getSearchShopGoodsList 获取搜索商品商铺list
     * @apiVersion 1.0.0
     * @apiName getSearchShopGoodsList
     * @apiGroup Pay
     * @apiParam {string}  guid 登录标识
     * @apiParam {int}  pagesize 每页有几条信息
     * @apiParam {int}  page 第几页
     * @apiParam {String}  keyword 关键词
     * @apiParam {String}  lat 经度
     * @apiParam {String}  lng 纬度
     */
    @PostMapping("/getSearchShopGoodsList")
    public WxMiniResponse getSearchShopGoodsList(@RequestBody MySearchQueryParam mySearchQueryParam) throws Exception {

        isCheckLogin(mySearchQueryParam.getGuid());
        if(currentStaff!=null&&currentStaff.getId()>0){
            myStaffSearchService.setSearchKeyword(mySearchQueryParam.getKeyword(),currentStaff.getId(),"search",0);
        }
        AliPushSearchDoc aliPushSearchDoc = new AliPushSearchDoc();
        Map  s =  aliPushSearchDoc.queryTextByShops(mySearchQueryParam);
        mySearchQueryParam.setType(1);
        Map  b =  aliPushSearchDoc.queryTextByGoods(mySearchQueryParam);
        Map map = new HashMap();
        map.put("shopData",s.get("data"));
        map.put("shopTotal",s.get("total"));
        map.put("goodsData",b.get("data"));
        map.put("goodsTotal",b.get("total"));
        return WxMiniResponse.ok(map);
   //     List list =  aliyunUtils.SearchImageByText(mySearchQueryParam,myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());

//        List keywordList = new ArrayList<>();
//        List keywordList1 = new ArrayList<>();
//        if(mySearchQueryParam.getKeyword()!=null) {
//            String keyword = Jsoup.clean(mySearchQueryParam.getKeyword(), Safelist.none());
//            for (int i = 0; i < element.length; i++) {
//                keyword = keyword.replace(element[i], "×");
//            }
//            JSONObject jsonObject = aliyunUtils.aliNlp(keyword,myStaticConfig.getAccessKeyId(),myStaticConfig.getAccessKeySecret());
//            if(jsonObject.getString("success").equals("true")){
//                keywordList = (List) jsonObject.get("result");
//                List finalKeywordList = new ArrayList();
//                for(Object ob:keywordList)
//                {
//                    Map map = (Map) ob;
//                    if(!map.get("synonym").equals("")){
//                        Map map1 = new HashMap();
//                        map1.put("synonym","");
//                        map1.put("weight",map.get("weight"));
//                        map1.put("tag",map.get("tag"));
//                        map1.put("word",map.get("synonym"));
//                        finalKeywordList.add(map1);
//
//                    }
//                }
//                keywordList.addAll(finalKeywordList);
//                keywordList1 = (List) keywordList.stream()
//                        .sorted((o1, o2) -> {
//                            JSONObject obj1 = new JSONObject((Map) o1); // 直接转 JSONObject
//                            JSONObject obj2 = new JSONObject((Map) o2);
//                            double weight1 = obj1.getDouble("weight");
//                            double weight2 = obj2.getDouble("weight");
//                            return Double.compare(weight2, weight1);
//                        }).collect(Collectors.toList());
//
//            }
//
//            keyword = keyword.replace(" ", "%");
//            mySearchQueryParam.setKeyword(keyword);
//        }
//        Map searchPageDto = mySearchService.getSearchShopGoodsList(mySearchQueryParam,keywordList1);
       // return null;
    }

    @Autowired
    MyStaffShopGoodsService myStaffShopGoodsService;

    @Autowired
    MyStaffShopService myStaffShopService;

    @Autowired
    MyStaffService myStaffService;


    @PostMapping("/getSearchImage")
    public WxMiniResponse getSearchImage() throws Exception {
        AliPushSearchDoc aliyunUtils = new AliPushSearchDoc();

        List<MyStaffShopGoods> list = myStaffShopGoodsService.selectList();
        if(list.size()>0){
            for (MyStaffShopGoods my:list){
                MySearchDto mySearch = new MySearchDto();
                if(my.getShopid()>0){
                    MyStaffShop myStaffShop = myStaffShopService.selectById(my.getShopid());
                    mySearch.setDistrictid(myStaffShop.getDistrictid());
                    mySearch.setLat(myStaffShop.getLat());
                    mySearch.setLng(myStaffShop.getLng());
                    mySearch.setStaffTitle(myStaffShop.getTitle());
                    mySearch.setStaffLogo(myStaffShop.getLogo());
                }else {
                    MyStaff myStaff = myStaffService.selectMyStaffById(my.getStaffId());
                    mySearch.setDistrictid(myStaff.getDistrictid());
                    mySearch.setLat(myStaff.getLat());
                    mySearch.setLng(myStaff.getLng());
                    mySearch.setStaffTitle(myStaff.getTitle()!=null?myStaff.getTitle():myStaff.getUserreal());
                    mySearch.setStaffLogo(myStaff.getLogo()==null?myStaff.getHeadimgurl():myStaff.getLogo());
                }
                mySearch.setFid(my.getShopid());
                mySearch.setPid(my.getId());
                mySearch.setName(my.getName());
                mySearch.setContent(my.getRemark());
                mySearch.setImg(my.getImage());
                mySearch.setVideo(my.getVideo());
                mySearch.setStaffId(my.getStaffId());

               aliyunUtils.addGoods(mySearch);
            }
        }

        return null;
    }

    @PostMapping("/getSearchShop")
    public WxMiniResponse getSearchShop() throws Exception {
        AliPushSearchDoc aliyunUtils = new AliPushSearchDoc();
        MyStaffShopQueryParam staffShopQueryParam = new MyStaffShopQueryParam();
        List<MyStaffShopDto> list = myStaffShopService.selectList(staffShopQueryParam);
        if(list.size()>0){
            for (MyStaffShopDto my:list){
                MySearchDto mySearch = new MySearchDto();
                mySearch.setDistrictid(my.getDistrictid());
                mySearch.setLat(my.getLat());
                mySearch.setLng(my.getLng());
                mySearch.setPid(my.getId());
                mySearch.setName(my.getTitle());
                mySearch.setContent(my.getIntro());
                mySearch.setLogo(my.getLogo());
                mySearch.setStaffId(my.getStaffId());
                mySearch.setRegion(my.getRegion());
                mySearch.setAddress1(my.getAddress1());
                mySearch.setAddress2(my.getAddress2());
                aliyunUtils.addShop(mySearch);
            }
        }
        return null;
    }


    @PostMapping("/getSearchCircle")
    public WxMiniResponse getSearchCircle() throws Exception {
        AliPushSearchDoc aliyunUtils = new AliPushSearchDoc();
        MyStaffQueryParam staffShopQueryParam = new MyStaffQueryParam();
        List<MyStaff> list = myStaffService.selectMyStaffList(staffShopQueryParam);
        if(list.size()>0){
            for (MyStaff my:list){
                MyCircle myCircle = myCircleService.selectOneByStaffId(my.getId());
                MySearchDto mySearch = new MySearchDto();
                if(!ObjectUtils.isEmpty(myCircle)) {
                    mySearch.setDistrictid(ObjectUtils.isEmpty(my.getDistrictid()) ? myCircle.getDistrictid() : my.getDistrictid());
                    mySearch.setLat(ObjectUtils.isEmpty(my.getLat()) ? myCircle.getLat() : my.getLat());
                    mySearch.setLng(ObjectUtils.isEmpty(my.getLng()) ? myCircle.getLng() : my.getLng());
                    mySearch.setPid(myCircle.getId());
                    mySearch.setStaffId(my.getId());
                    mySearch.setName(myCircle.getTitle());
                    mySearch.setContent(myCircle.getContent());
                    mySearch.setImg(myCircle.getImage());
                    mySearch.setVideo(myCircle.getImage());
                    mySearch.setLogo(myCircle.getLogo());
                    mySearch.setStaffLogo(my.getLogo());
                    mySearch.setRegion(myCircle.getRegion());
                    mySearch.setAddress(myCircle.getAddress());
                    mySearch.setStaffAddress1(my.getAddress1());
                    mySearch.setStaffAddress2(my.getAddress2());
                    mySearch.setStaffTitle(my.getTitle());
                    mySearch.setStaffHeadimgurl(my.getHeadimgurl());
                    aliyunUtils.addCircle(mySearch);
                }
            }
        }
        return null;
    }

}
